package com.luqili.utils.pub.json.jackjson;


import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.DateSerializer;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;

import java.io.IOException;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

/**
 * 序列化Json
 *
 * @author luqili
 */
public class JsonSerializerByDate extends DateSerializer {
    private String customFormat;
    private TimeZone tz;
    private Locale loc;

    public JsonSerializerByDate() {

    }

    public JsonSerializerByDate(String customFormat, TimeZone tz, Locale loc) {
        this.customFormat = customFormat;
        this.tz = tz;
        this.loc = loc;

    }

    @Override
    public void serialize(Date value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        if (value == null) {
            gen.writeString("");
            return;
        }
        if (loc == null) {
            loc = Locale.CHINA;
        }
        if (tz == null) {
            tz = TimeZone.getTimeZone("Asia/Shanghai");
        }
        if (StringUtils.isBlank(customFormat)) {
            customFormat = "yyyy-MM-dd HH:mm:ss";
        }
        gen.writeString(DateFormatUtils.format(value, customFormat, tz, loc));
    }

    @Override
    public JsonSerializer<?> createContextual(SerializerProvider serializers, BeanProperty property) throws JsonMappingException {
        JsonFormat.Value format = findFormatOverrides(serializers, property, handledType());
        if (format == null) {
            return this;
        } else {
            return new JsonSerializerByDate(format.getPattern(), format.getTimeZone(), format.getLocale());
        }
    }
}
